/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nus.application.web.base.filter;

import com.nus.dataaccess.dao.util.HibernateUtil;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author robin.foe
 */
@WebFilter(urlPatterns = "/*", filterName = "hibernate_filter")
public class Hibernatefilter implements Filter {

    private static Log log = LogFactory.getLog(Hibernatefilter.class);

    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("Servlet filter init, now opening/closing a Session for each request.");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        // There is actually no explicit "opening" of a Session, the
        // first call to HibernateUtil.beginTransaction() in control
        // logic (e.g. use case controller/event handler) will get
        // a fresh Session.
        try {
            chain.doFilter(request, response);

            try {
                //log.info("COMMIT ");
                // Commit any pending database transaction.
                HibernateUtil.commitTransaction();
            } catch (Exception ex) 
            {ex.printStackTrace();
//                if (log.isErrorEnabled()) {
//                    log.error(ex);
//                }
            }

        } finally {
            try {
                //log.info("Close Session");
                // No matter what happens, close the Session.
                HibernateUtil.closeSession();
            } catch (Exception ex) {
                ex.printStackTrace();
//                if (log.isErrorEnabled()) {
//                    log.error(ex);
//                }
            }

        }
    }

    public void destroy() {
    }
}
